package impl

import (
	"context"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/sqlbuilder"
)
import "gitee.com/zhangyu520cw/restful-api-demo-g7/apps/host"

// 业务处理层

func (i *HostServiceImpl) CreateHost(ctx context.Context, ins *host.Host) (*host.Host, error) {
	// 直接打印日志
	i.l.Named("create").Debug("create host")
	i.l.Info("create host")
	// 带format 的日志打印，fmt.Sprintf()
	i.l.Debugf("create host %s", host.AppName)
	// 携带额外meta数据，常用于Trace系统
	i.l.With(logger.NewAny("request-id", "req01")).Debug("create host with req01")
	//校验数据合法性
	if err := ins.Validate(); err != nil {
		return nil, err
	}
	// 默认值填充
	ins.InjectDefault()

	// 有dao 模块 负责 把对象入库
	err := i.save(ctx, ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}
func (i *HostServiceImpl) QueryHost(ctx context.Context, req *host.QueryHostRequest) (*host.HostSet, error) {
	b := sqlbuilder.NewBuilder(queryHostSQL)
	if req.Keywords != "" {
		// r.`na
		//	me` LIKE ? OR r.description LIKE ? OR r.private_ip LIKE ? OR r.public_ip LIKE ?
		// 10.10.1, 接口测试
		b.Where("r.`name` LIKE ? OR r.description LIKE ? OR r.private_ip LIKE ? OR r.public_ip LIKE ?",
			"%"+req.Keywords+"%",
			"%"+req.Keywords+"%",
			req.Keywords+"%",
			req.Keywords+"%",
		)
	}
	b.Limit(req.OffSet(), req.GetPageNum())
	querySQL, args := b.Build()
	i.l.Debugf("query sql: %s, args: %v", querySQL, args)

	// query stmt ,构建一个Prepare语句
	stmt, err := i.db.PrepareContext(ctx, querySQL)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.QueryContext(ctx, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	set := host.NewHostSet()
	for rows.Next() {
		// 每扫描一行，就需要读取出来
		// h.cpu, h.memory, h.gpu_spec,h,gpu_amount,
		ins := host.NewHost()
		//var s string
		if err := rows.Scan(&ins.Id, &ins.Vendor, &ins.Region, &ins.CreateAt, &ins.ExpireAt,
			&ins.Type, &ins.Name, &ins.Description, &ins.Status, &ins.UpdateAt, &ins.SyncAt,
			&ins.Account, &ins.PublicIP, &ins.PrivateIP,
			&ins.CPU, &ins.Memory, &ins.GPUSpec, &ins.GPUAmount,
			&ins.OSType, &ins.OSName, &ins.SerialNumber); err != nil {
			return nil, err
		}
		set.Add(ins)
	}
	// 统计生成的数据
	countSQL, args := b.BuildCount()
	i.l.Debugf("count sql: %s, args: %v", countSQL, args)
	countStmt, err := i.db.PrepareContext(ctx, countSQL)
	if err != nil {
		return nil, err
	}
	defer countStmt.Close()
	if err := countStmt.QueryRowContext(ctx, args...).Scan(&set.Total); err != nil {
		return nil, err
	}
	return set, nil
}
func (i *HostServiceImpl) DescribeHost(ctx context.Context, req *host.QueryHostRequest) (*host.Host, error) {
	return nil, nil
}
func (i *HostServiceImpl) UpdateHost(ctx context.Context, req *host.UpdataHostRequest) (*host.Host, error) {
	return nil, nil
}
func (i *HostServiceImpl) DeleteHost(ctx context.Context, req *host.DeleteHostRequest) (*host.Host, error) {
	return nil, nil
}
